package edu.hit.crawler.http;

import java.io.IOException;
import java.net.URL;
import org.apache.log4j.Logger;

public class Decode {

	public static final Logger LOGGER = Logger.getLogger(Decode.class);
	private static int maxContent = 1024 * 1024;

	public static byte[] processGzipEncoded(byte[] compressed, URL url)
			throws IOException {

		if (LOGGER.isTraceEnabled()) {
			LOGGER.trace("uncompressing....");
		}

		byte[] content;
		if (maxContent >= 0) {
			content = GZIPUtils.unzipBestEffort(compressed, maxContent);
		} else {
			content = GZIPUtils.unzipBestEffort(compressed);
		}

		if (content == null)
			throw new IOException("unzipBestEffort returned null");

		if (LOGGER.isTraceEnabled()) {
			LOGGER.trace("fetched " + compressed.length
					+ " bytes of compressed content (expanded to "
					+ content.length + " bytes) from " + url);
		}
		return content;
	}

	public static byte[] processDeflateEncoded(byte[] compressed, URL url)
			throws IOException {

		if (LOGGER.isTraceEnabled()) {
			LOGGER.trace("inflating....");
		}

		byte[] content = DeflateUtils.inflateBestEffort(compressed,
				maxContent);

		if (content == null)
			throw new IOException("inflateBestEffort returned null");

		if (LOGGER.isTraceEnabled()) {
			LOGGER.trace("fetched " + compressed.length
					+ " bytes of compressed content (expanded to "
					+ content.length + " bytes) from " + url);
		}
		return content;
	}
}
